#include "sicasm.h"

SYMTAB symtab;
int locctr,error=0,linecount=0;
char label[9],opcode[7],operand[9];

void readline(FILE *f)
{
 char *line;
 int i;
 do{
 line = new char[80];
// fgets(line,80,f);
 fscanf(f,"%[^\n]",line);
 fgetc(f);
 linecount++;
 if (strlen(line)<30)
  {
  for(i=strlen(line);i<=25;i++) line[i]=' ';
  line[29]='\0';
  }
 for(i=0;i<8;i++) label[i]=line[i];
 label[9]='\0';
 for(i=9;i<15;i++) opcode[i-9]=line[i];
 opcode[7]='\0';
 for(i=17;i<25;i++) operand[i-17]=line[i];
 operand[9]='\0';
 delete line;
 } while(label[0]=='.'); //skipping comments
}

void pass1(FILE *src)
{
 FILE *intf;
 int newloc;
 intf = fopen("OUT.INT","wb");
 readline(src);
 if (!strcmp(opcode,"START "))
  {
   intrec.addr=locctr=atoi(operand);
   startaddr=newloc=locctr;
   strcpy(intrec.label,label);
   strcpy(intrec.opcode,opcode);
   strcpy(intrec.operand,operand);
   fwrite(&intrec,sizeof(intrec),1,intf);
   readline(src);
  }
 else newloc=locctr=0;

 while (strcmp(opcode,"END   ")) {
    if (strcmp(label,"        ")) //if label field not empty
     {
       if (symtab.search(label)!=-1)
	 {
	 error++;
	 cout<<"\nLine #"<<linecount<<": Error - Duplicate Symbol: ";
	 cout<<label;
	 }
       else symtab.insert(label,locctr);//new symbol inserted
     }//no symbol in label field
    if (opcodesearch(opcode)!=-1) newloc=3;
    else if (!strcmp(opcode,"WORD  ")) newloc=3;
    else if (!strcmp(opcode,"RESW  ")) newloc=3*atoi(operand);
    else if (!strcmp(opcode,"RESB  ")) newloc=atoi(operand);
    else if (!strcmp(opcode,"BYTE  ")) newloc=3;
    else {
      error++;
      cout<<"\nLine #"<<linecount<<": Error - Invalid Opcode: ";
      cout<<opcode;
    }

   intrec.addr=locctr;
   strcpy(intrec.label,label);
   strcpy(intrec.opcode,opcode);
   strcpy(intrec.operand,operand);
   fwrite(&intrec,sizeof(intrec),1,intf); //write line to int file
   locctr+=newloc;
   readline(src);
 }//end of while

  intrec.addr=locctr;
  strcpy(intrec.label,label);
  strcpy(intrec.opcode,opcode);
  strcpy(intrec.operand,operand);
  fwrite(&intrec,sizeof(intrec),1,intf); //write line to int file

  proglen=locctr-startaddr;
  intrec.addr=proglen;
  fwrite(&intrec,sizeof(intrec),1,intf);
  fclose(intf);
}

